# 人生苦短，我用python
# @Time : 2021/9/15 14:13
# @Author : shiChao
# @File : mysql.py
# @Desc : mysql操作
import threading
import pymysql


class Mysql:
    conn = None
    cursor = None
    _instance_lock = threading.Lock()

    # 初始化
    def __new__(cls, *args, **kwargs):
        if not hasattr(Mysql, "_instance"):
            with Mysql._instance_lock:
                if not hasattr(Mysql, "_instance"):
                    Mysql._instance = object.__new__(cls)
        return Mysql._instance

    """
        初始化MySQL
        host： 域名
        username： 账号
        password： 密码
        db： 查询数据库
    """
    def __init__(self, host, username, password, db, charset='utf8', port=3306):
        self.host = host
        self.username = username
        self.password = password
        self.db = db
        self.charset = charset
        self.port = port

    # 连接MySQL
    def connect(self):
        self.conn = pymysql.connect(host=self.host, port=self.port, user=self.username, password=self.password,
                                    db=self.db, charset=self.charset)
        self.cursor = self.conn.cursor()

    # 关闭MySQL
    def close(self):
        self.cursor.close()
        self.conn.close()

    # 查询
    def get(self, sql, params=()):
        result = None
        try:
            self.connect()
            self.cursor.execute(sql, params)
            result = self.cursor.fetchone()
            self.close()
        except Exception as e:
            print(e)
        return result

    # 查询
    def select(self, sql, params=()):
        list_data = ()
        try:
            self.connect()
            self.cursor.execute(sql, params)
            list_data = self.cursor.fetchall()
            self.close()
        except Exception as e:
            print(e)
        return list_data

    # 添加
    def insert(self, sql, params=()):
        return self.__edit(sql, params)

    # 修改
    def update(self, sql, params=()):
        return self.__edit(sql, params)

    # 删除
    def delete(self, sql, params=()):
        return self.__edit(sql, params)

    def __edit(self, sql, params):
        count = 0
        try:
            self.connect()
            count = self.cursor.execute(sql, params)
            self.conn.commit()
            self.close()
        except Exception as e:
            print(e)
        return count

